import styles from '../styles.less';
import {Modal, Pagination, Space, Table, Tag} from 'antd';
import {useCallback, useEffect} from 'react';
import Opera from './Opera';
import {connect, useAccess} from 'umi';
import {ExclamationCircleFilled} from '@ant-design/icons';
import {nowrapColumns} from '@/utils/utils';

const DataTable = (props) => {

  const {dispatch, dataTable, submitting, loading} = props;
  const {setItems, setDataForm, tablePayload, setTablePayload} = props.data;
  const access = useAccess();

  /* 获取列表 */
  const fetchList = useCallback((payload) => {
    dispatch({
      type: 'PMallPkg/fetchList',
      payload: payload,
    });
  }, [dispatch]);

  /* 查询监听 */
  useEffect(() => {
    fetchList(tablePayload);
  }, [fetchList, tablePayload]);

  /* 项目 */
  function items(e, record) {
    e.preventDefault();
    setItems({
      visible: true,
      title: '项目管理',
      data: record,
    });
    return false;
  }

  /* 编辑 */
  function edit(e, record) {
    e.preventDefault();
    setDataForm({
      visible: true,
      title: '编辑操作',
      data: record,
    });
    return false;
  }

  /* 删除 */
  function del(e, record) {
    e.preventDefault();
    if (!submitting) {
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleFilled/>,
        content: '是否确定删除数据？',
        onOk() {
          dispatch({
            type: 'PMallPkg/del',
            payload: [record.id],
            callback: () => {
              setTablePayload({...tablePayload, pageNum: 1});
            },
          });
        },
      });
    }
    return false;
  }

  /* 更新状态 */
  function status(e, record) {
    e.preventDefault();
    if (!submitting) {
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleFilled/>,
        content: record.status === 1 ? '是否确定下架？' : '是否确定上架',
        onOk() {
          dispatch({
            type: 'PMallPkg/status',
            payload: record.id,
            callback: () => {
              setTablePayload({...tablePayload, pageNum: 1});
            },
          });
        },
      });
    }
    return false;
  }

  /* 更新状态 */
  function sellStatus(e, record) {
    e.preventDefault();
    if (!submitting) {
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleFilled/>,
        content: record.sellStatus === 1 ? '是否确定售罄？' : '是否确定售卖',
        onOk() {
          dispatch({
            type: 'PMallPkg/sellStatus',
            payload: record.id,
            callback: () => {
              setTablePayload({...tablePayload, pageNum: 1});
            },
          });
        },
      });
    }
    return false;
  }

  const columns = [
    {
      title: '序号',
      width: 70,
      align: 'center',
      fixed: 'left',
      render: ({}, {}, index) => (
        <span>
          {(tablePayload.pageNum - 1) * tablePayload.pageSize + index + 1}
        </span>
      ),
    },
    {
      title: '套餐名称',
      dataIndex: 'name',
      align: 'left',
      width: 200,
      ellipsis: true,
    },
    {
      title: '套餐项目',
      dataIndex: 'mallPkgItemCount',
      align: 'center',
      render: (_, record) => {
        if (!access.mall_pkgItem_list) {
          return (<span>-</span>);
        }
        return (
          <span style={{color: '#1d39c4', cursor: 'pointer'}}
                onClick={e => items(e, record)}>项目（{record.mallPkgItemCount}）</span>
        );
      },
    },
    {
      title: '当前售价',
      dataIndex: 'sellPrice',
      align: 'center',
      render: (_, record) => {
        return (
          <span style={{color: '#d4380d'}}>￥ {(record.sellPrice / 100).toFixed(2)}</span>
        );
      },
    },
    {
      title: '现有库存',
      dataIndex: 'stock',
      align: 'center',
      render: (_, record) => {
        return (
          <span style={{color: 'green'}}>{record.stock}</span>
        );
      },
    },
    {
      title: '有效期天',
      dataIndex: 'indate',
      align: 'center',
      render: (_, record) => {
        return (
          <span>{record.indate === 0 ? '永久有效' : `${record.indate} 天`}</span>
        );
      },
    },
    {
      title: '限购类型',
      dataIndex: 'limitType',
      align: 'center',
      render: (_, record) => {
        let text;
        if (record.limitType === 0) {
          text = '不限购';
        }
        if (record.limitType === 1) {
          text = `${record.limitNum}次/天`;
        }
        if (record.limitType === 2) {
          text = `${record.limitNum}次/周`;
        }
        if (record.limitType === 3) {
          text = `${record.limitNum}次/月`;
        }
        if (record.limitType === 4) {
          text = `${record.limitNum}次/年`;
        }
        return (
          <span>{text}</span>
        );
      },
    },
    {
      title: '售罄状态',
      dataIndex: 'sellStatus',
      align: 'center',
      render: (_, record) => {
        return (
          <Tag color={record.sellStatus === 1 ? 'geekblue' : 'volcano'}>
            {record.sellStatus === 1 ? '售卖' : '售罄'}
          </Tag>
        );
      },
    },
    {
      title: '当前状态',
      dataIndex: 'status',
      align: 'center',
      render: (_, record) => {
        return (
          <Tag color={record.status === 1 ? 'geekblue' : 'volcano'}>
            {record.status === 1 ? '已上架' : '已下架'}
          </Tag>
        );
      },
    },
    {
      title: '真实销量',
      dataIndex: 'sellNum',
      align: 'center',
      render: (_, record) => {
        return (
          <span>{record.sellNum}</span>
        );
      },
    },
    {
      title: '排序属性',
      dataIndex: 'orderby',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'option',
      align: 'center',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space size='small'>
          {access?.mall_pkg_status && (
            <a onClick={e => status(e, record)}>{record.status === 1 ? '下架' : '上架'}</a>
          )}
          {access?.mall_pkg_sellStatus && (
            <a onClick={e => sellStatus(e, record)}>{record.sellStatus === 1 ? '售罄' : '售卖'}</a>
          )}
          {access?.mall_pkg_edit && (
            <a onClick={e => edit(e, record)}>编辑</a>
          )}
          {access?.mall_pkg_del && (
            <a onClick={e => del(e, record)}>删除</a>
          )}
        </Space>
      ),
    },
  ];

  return (
    <>
      <div className={styles.myDataTable}>
        <Opera data={{setDataForm}}/>
        <Table
          className={styles.myTable} bordered={false} size={'middle'} columns={nowrapColumns(columns, dataTable.list)}
          dataSource={dataTable.list} rowKey={'id'}
          pagination={false} scroll={{y: '100%'}} loading={loading}
        />
      </div>
      <Pagination
        pageSize={tablePayload.pageSize} current={tablePayload.pageNum} total={dataTable.total}
        className={styles.myPagination} size={'default'} hideOnSinglePage={false}
        showTotal={(total) => {
          return `共 ${total} 条记录`;
        }}
        pageSizeOptions={[15, 30, 60, 120]}
        showSizeChanger showQuickJumper={true}
        onChange={(page, pageSize) => {
          setTablePayload({...tablePayload, pageNum: page, pageSize: pageSize});
        }}
      />
    </>

  );
};

export default connect(({loading, PMallPkg}) => {
  return {
    loading: loading.effects['PMallPkg/fetchList'],
    submitting: loading.effects['PMallPkg/del'] || loading.effects['PMallPkg/status'] || loading.effects['PMallPkg/sellStatus'],
    dataTable: PMallPkg.dataTable,
  };
})(DataTable);
